<template>
  <div>
    <Drawer
      width="100%"
      :title="title"
      placement="right"
      v-model:visible="visible"
      :footer-style="{ textAlign: 'right' }"
      :destroy-on-close="true"
      @close="onClose"
    >
      <template #closeIcon>
        <arrow-left-outlined />
      </template>
      <Card>
        <Form ref="formRef" :model="formState" :rules="rules">
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="链路名称" name="linkName">
                <Input v-model:value="formState.linkName" placeholder="请输入" :style="{ width: '400px' }"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="链路描述">
                <Textarea v-model:value="formState.linkDesc" :rows="6" placeholder="请输入"></Textarea>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="12">
              <FormItem
                label="命名空间"
                name="namespace"
                :rules="[{ required: true, message: '命名空间不能为空', trigger: 'change' }]"
              >
                <Select
                  v-model:value="formState.namespace"
                  :options="namespaceList"
                  placeholder="请选择"
                  :style="{ width: '400px' }"
                  mode="multiple"
                >
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="24">
              <FormItem
                label="工作负载"
                name="namespace"
                :rules="[{ required: true, message: '工作负载不能为空', trigger: 'change' }]"
              >
                <Transfer
                  v-model:target-keys="targetKeys"
                  :data-source="transferData"
                  :disabled="disabled"
                  :rowKey="
                    (record) => {
                      return record.id + record.version;
                    }
                  "
                  :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
                  :show-select-all="false"
                  @change="onChange"
                  :locale="{ itemUnit: '项', itemsUnit: '项' }"
                >
                  <template
                    #children="{
                      direction,
                      filteredItems,
                      selectedKeys,
                      disabled: listDisabled,
                      onItemSelectAll,
                      onItemSelect,
                    }"
                  >
                    <Table
                      :row-selection="
                        getRowSelection({
                          disabled: listDisabled,
                          selectedKeys,
                          onItemSelectAll,
                          onItemSelect,
                        })
                      "
                      :columns="direction === 'left' ? leftColumns : rightColumns"
                      :data-source="filteredItems"
                      size="small"
                      :style="{ pointerEvents: listDisabled ? 'none' : null }"
                      :custom-row="
                        ({ key, disabled: itemDisabled }) => ({
                          onClick: () => {
                            if (itemDisabled || listDisabled) return;
                            onItemSelect(key, !selectedKeys.includes(key));
                          },
                        })
                      "
                    />
                  </template>
                </Transfer>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>
      <template #footer>
        <Button style="margin-right: 8px" type="primary" @click="submit">提交</Button>
        <Button @click="onClose">取消</Button>
      </template>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import {
  Drawer,
  Card,
  Row,
  Col,
  Form,
  FormItem,
  Button,
  Table,
  Textarea,
  Input,
  Select,
  Transfer,
  message,
} from 'ant-design-vue';
import { ArrowLeftOutlined } from '@ant-design/icons-vue';
import { reactive, ref, watchEffect } from 'vue';
import {
  createLink,
  editLink,
  getLinkDetail,
  getNamespaceList,
  getWorkLoad,
} from '/@/api/upgrade-center/grayscale/linkManagement/linkManagement';
import { Rule } from 'ant-design-vue/lib/form';
import { rightTableColumns, leftTableColumns } from '/@/views/upgrade-center/grayscale/linkManagement/data';
// 校验
const formRef = ref();
const checkName = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('链路名不能为空'));
  }
};
const rules: Record<string, Rule[]> = {
  linkName: [{ required: true, validator: checkName, trigger: 'change' }],
};
const handleValidate = async () => {
  return formRef.value.validate();
};
const formState = reactive({
  linkName: undefined,
  linkDesc: undefined,
  namespace: [],
});

const namespaceList = ref([]);
const visible = ref(false);
const title = ref();
// 获取所有命名空间
const getData = async () => {
  namespaceList.value = await getNamespaceList();
};
// 创建
const useCreate = async () => {
  visible.value = true;
  title.value = '创建链路';
  getData();
};
// 穿梭框
interface TransferData {
  id: string;
  namespace: string;
  appName: string;
  componentName: string;
  deployment: string;
  version: string;
}
let originTargetKeys: string[] = [];
const targetKeys = ref<string[]>(originTargetKeys);
const transferData = ref<TransferData[]>([]);
const selectedCompoList = ref([]);
// 获取该记录的命名空间
const getSelectedNamespace = (compoList) => {
  let arr = [];
  for (let i = 0; i < compoList.length; i++) {
    arr.push(compoList[i].namespace);
  }
  return Array.from(new Set(arr));
};

const id = ref();
const routeLinkKey = ref();
// 编辑
const useEdit = async (record) => {
  title.value = '编辑链路';
  formState.linkName = record.name;

  id.value = record.id;
  routeLinkKey.value = record.routeLinkKey;
  let detailData = await getLinkDetail(record.id);
  selectedCompoList.value = detailData.componentList;
  formState.linkDesc = detailData.description;
  formState.namespace = getSelectedNamespace(detailData.componentList);
  for (let i = 0; i < detailData.componentList.length; i++) {
    originTargetKeys.push(detailData.componentList[i].id + detailData.componentList[i].version);
  }
  targetKeys.value = originTargetKeys;
  visible.value = true;
  getData();
};

type tableColumn = Record<string, string>;
const workLoad = ref();
watchEffect(async () => {
  if (formState.namespace && formState.namespace.length != 0) {
    workLoad.value = await getWorkLoad(formState.namespace);
    transferData.value = workLoad.value;
  } else {
    transferData.value = [];
    targetKeys.value = [];
  }
});

const disabled = ref<boolean>(false);

const leftColumns = ref<tableColumn[]>(leftTableColumns);
const rightColumns = ref<tableColumn[]>(rightTableColumns);

const onChange = (nextTargetKeys: string[]) => {
  selectedCompoList.value = [];

  for (let i = 0; i < nextTargetKeys.length; i++) {
    let res = transferData.value.filter((item) => {
      return item.id + item.version == nextTargetKeys[i];
    });
    selectedCompoList.value.push(res[0]);
  }
  if (selectedCompoList.value[0].deployment !== '--') {
    message.success('提交后重启应用服务');
  }
};

const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }: Record<string, any>) => {
  return {
    getCheckboxProps: (item: Record<string, string | boolean>) => ({
      disabled: disabled || item.disabled,
    }),
    onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
      const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({ key }: Record<string, string>, selected: boolean) {
      onItemSelect(key, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};

const onClose = () => {
  formRef.value.clearValidate();
  visible.value = false;
  formState.linkDesc = undefined;
  formState.linkName = undefined;
  formState.namespace = [];
  transferData.value = [];
  targetKeys.value = [];
  originTargetKeys = [];
};
defineExpose({ useCreate, useEdit });

// 提交
let createEditParams = {
  componentCount: 0,
  componentList: [],
  createdBy: 0,
  createdTime: '',
  description: '',
  id: 0,
  isBuiltIn: false,
  isDel: false,
  lastUpdateBy: 0,
  lastUpdateTime: '',
  name: '',
  routeLinkKey: '',
  ruleCount: 0,
};
const emit = defineEmits(['getNewRecord']);
const submit = async () => {
  handleValidate();
  if (formState.linkName && formState.namespace.length !== 0) {
    if (targetKeys.value.length != 0) {
      createEditParams.description = formState.linkDesc;
      createEditParams.name = formState.linkName;
      createEditParams.componentCount = targetKeys.value.length;
      createEditParams.componentList = selectedCompoList.value;
      createEditParams.id = id.value;
      createEditParams.routeLinkKey = routeLinkKey.value;

      if (title.value == '创建链路') {
        let res = await createLink(createEditParams);
        if (res) {
          message.success(res);
        }
      }
      if (title.value == '编辑链路') {
        let res = await editLink(createEditParams);
        if (res) {
          message.success(res);
        }
      }

      emit('getNewRecord');
      onClose();
    } else {
      message.warning('工作负载不能为空');
    }
  }
};
</script>
